import math
from endOfSanity import *

class basicEdge:

    width = 0.005    

    def __init__(self,start, end,ID):
        self.startNode = start
        self.endNode = end
        self.ID = "edge" + str(ID)
        self.priority = 1
          
    def __repr__(self):
        return "(" + str(self.startNode.ID) + "," + str(self.endNode.ID) + ")"
       
    def isInEdge(self, x, y):
        x1, y1 = self.startNode.getXY()
        x2, y2 = self.endNode.getXY()
        d1 = math.sqrt((x1 - x) ** 2 + (y1 - y) ** 2)
        d2 = math.sqrt((x2 - x) ** 2 + (y2 - y) ** 2)        
        d = self.length()
        return (d1 + d2) / (d) - 1 < 0.001 / d #TODO: cos lepszego ;)       
            
        
    def length(self):
        x1 = self.startNode.getX()
        y1 = self.startNode.getY()
        x2 = self.endNode.getX()
        y2 = self.endNode.getY()        
        return math.sqrt( (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2))
        
    def findIntersection(self, sx, sy, ex, ey):
    
        def det(a, b, c, d):
            return a * d - b * c
    
        nsx, nsy = self.startNode.getXY()
        nex, ney = self.endNode.getXY()
        
        if len(set([(sx, sy), (ex, ey), (nsx, nsy), (nex, ney)])) < 4:
            return None
        
        """
        t * (sx - ex) + s * (nex - nsx) = nex - ex
        t * (sy - ey) + s * (ney - nsy) = ney - ey
        """        
        md = det(sx - ex, nex - nsx, sy - ey, ney - nsy)
        td = det(nex - ex, nex - nsx, ney - ey, ney - nsy)  
        sd = det(sx - ex, nex - ex, sy - ey, ney - ey)
        
        if md == 0:    
            return None
        alpha = 1.0 - float(td) / md
        beta = 1.0 - float(sd) / md
        if 0.0 <= alpha <= 1.0 and 0.0 <= beta <= 1.0:
            return alpha
        return None

    def snap(self, x, y):
        sx, sy = self.startNode.getXY()
        ex, ey = self.endNode.getXY()
        len = math.sqrt((ex - sx) ** 2 + (ey - sy) ** 2)
        dist = math.sqrt((x - sx) ** 2 + (y - sy) ** 2)
        alpha = min(1.0, dist / len)
        nx = ex * alpha + sx * (1.0 - alpha)
        ny = ey * alpha + sy * (1.0 - alpha)
        return nx, ny
        
